import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { IRequestInterceptors, ISelfRequestConfig } from './type'

class HttpRequest {
  instance: AxiosInstance
  interceptors?: IRequestInterceptors
  constructor(config: ISelfRequestConfig) {
    /**config定义类型 ISelfRequestConfig*/
    this.instance = axios.create(config)
    this.interceptors = config.interceptors

    // 可以修改顺序
    // 从config中取出的拦截器都是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.requestInterceptorCatch
    )

    // 添加所有的实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        console.log('所有的实例都有的拦截器请求')
        return config
      },
      (err) => {
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        console.log('所有的实例都有的拦截器响应')
        return res.data
      },
      (err) => {
        return err
      }
    )
  }

  request<T>(config: ISelfRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      // 1.单个请求对config做处理
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }
      this.instance
        .request<unknown, T>(config)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
}

export default HttpRequest
